import { _decorator, assetManager, ImageAsset, Texture2D, SpriteFrame } from 'cc';
const { ccclass, property } = _decorator;
import * as fgui from "fairygui-cc";

export default class PlayerBoxEntity {
  public node: fgui.GComponent;

  private _energyLabel: fgui.GComponent;
  private _customAvatar: fgui.GImage;
  private _progress: fgui.GProgressBar

  private _avatar: fgui.GLoader;

  private _spriteFrame: SpriteFrame;

  constructor(node: fgui.GComponent) {
    this.node = node;

    this._energyLabel = this.node.getChild('n10', fgui.GComponent)
    this._customAvatar = this.node.getChild('n1', fgui.GImage)
    this._progress = this.node.getChild('n11', fgui.GProgressBar)

    this._avatar = this.node.getChild('n0', fgui.GLoader)
    this._avatar.width = 70
    this._avatar.height = 70
  }

  public updatePlayerInfo(playerInfo: playerInfo) {

    // assetManager.releaseAsset(this._avatar.texture);

    if (this._spriteFrame) {
      // assetManager.releaseAsset(this._spriteFrame);
      // this._spriteFrame.decRef();
      // this._spriteFrame = null;
    }

    assetManager.loadRemote<ImageAsset>(playerInfo.avatar, (err, imageAsset) => {
      if (err) {
        console.error(err);
        return;
      }

      this._spriteFrame = new SpriteFrame();
      const texture = new Texture2D();
      texture.image = imageAsset;
      this._spriteFrame.texture = texture;
      this._avatar.texture = this._spriteFrame;
    });

    // if (this._avatar.url) {
    //   this._avatar.url = null;
    //   this._avatar.url = playerInfo.avatar;
    // }

    this._energyLabel.text = `${playerInfo.shield}`
    this._progress.tweenValue(playerInfo.shield, 0.5)
    this._customAvatar.removeFromParent();
  }

  public updatePlayerAvatar() {

  }

  destroy() {

    console.log('destroyed', this._spriteFrame)
    this._avatar.texture = null;
    if (this._spriteFrame) {
      assetManager.releaseAsset(this._spriteFrame);
      this._spriteFrame.decRef();
      this._spriteFrame = null;
      console.log('destroyed --', this._spriteFrame)
    }

    this._avatar.dispose();
    this._avatar.removeFromParent();
    this.node.removeFromParent();
  }
}